<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 步骤条 -->
      <el-steps :active="activeName - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单区域 -->
      <el-form
        label-position="top"
        :rules="addTabsFormRules"
        :model="addTabsForm"
        ref="addTabsFormRef"
      >
        <!-- Tabs标签页 -->
        <el-tabs
          v-model="activeName"
          tab-position="left"
          style="height: 100%;"
          :before-leave="tabsBeforeLeave"
          @tab-click="clickTabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addTabsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addTabsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addTabsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addTabsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addTabsForm.goods_cat"
                :options="addCascaderOptions"
                :props="addCascaderProps"
                @change="addCascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyParamsData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="vals"
                  v-for="(vals, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyParamsData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input
            ></el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="uploadHandlePreview"
              :on-remove="uploadHandleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="uploadOnSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- 图片预览区域 -->
            <div class="demo-image__preview">
              <el-image
                style="width: 100px; height: 100px"
                :src="url"
                :preview-src-list="srcList"
              >
              </el-image>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addTabsForm.goods_introduce"></quill-editor>
            <!-- 添加商品 -->
            <el-button
              type="primary"
              style="margin-top: 20px;"
              @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeName: 0,
      // 表单数据对象
      addTabsForm: {
        goods_name: '',
        goods_price: '0',
        goods_number: '0',
        goods_weight: '0',
        // 级联选择器的选中节点的id
        goods_cat: [],
        // 上传图片临时地址
        pics: [],
        // 富文本编辑器
        goods_introduce: '',
        // 商品参数
        attrs: []
      },
      // 添加表单验证
      addTabsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          {
            required: true,
            trigger: 'blur'
          }
        ]
      },
      // 级联选择器数据源
      addCascaderOptions: [],
      // 级联选择器配置对象
      addCascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover',
        children: 'children'
      },
      // 商品参数数据
      manyParamsData: [],
      // 商品属性
      onlyParamsData: [],
      // 图片上传地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 设置上传的请求头部
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 封面地址
      url: '',
      // 预览图片路径地址
      srcList: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      console.log(res)
      // 数据
      this.addCascaderOptions = res.data
    },
    // 级联选择器的值发生改变的时候触发
    addCascaderChange() {
      console.log(this.addTabsForm.goods_cat)
      if (this.addTabsForm.goods_cat.length !== 3) {
        this.addTabsForm.goods_cat = []
      }
    },
    // 切换标签之前的钩子
    tabsBeforeLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addTabsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    // tab 被选中时触发
    async clickTabs() {
      if (this.activeName === '1') {
        const {
          data: res
        } = await this.$http.get(
          `categories/${this.getGoodsCateId}/attributes`,
          { params: { sel: 'many' } }
        )
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyParamsData = res.data
        console.log(this.manyParamsData)
      } else if (this.activeName === '2') {
        const {
          data: res
        } = await this.$http.get(
          `categories/${this.getGoodsCateId}/attributes`,
          { params: { sel: 'only' } }
        )
        this.onlyParamsData = res.data
        console.log(this.onlyParamsData)
      }
    },
    // 已上传的文件时的钩子
    uploadHandlePreview(file) {
      console.log(file)
    },
    // 文件列表移除文件时的钩子
    uploadHandleRemove(file) {
      // console.log(file)
      // 1. 获取将要删除的临时路径
      const filePath = file.response.data.tmp_path
      // 2. 从 pics 数组中，找到这个图片对应的索引值
      const index = this.addTabsForm.pics.findIndex(x => {
        return x.pic === filePath
      })
      this.addTabsForm.pics.splice(index, 1)
    },
    // 文件上传成功的时候的钩子
    uploadOnSuccess(response, file) {
      // 1. 拼接得到一个图片信息对象
      const picStr = { pic: response.data.tmp_path }
      // 2. 将图片信息对象，push 到pics数组中
      this.addTabsForm.pics.push(picStr)
      if (this.url.length === 0) {
        this.url = file.response.data.url
      }
      this.srcList.unshift(file.response.data.url)
      console.log(this.srcList)
    },
    // 添加商品
    addGoods() {
      // console.log(this.addTabsForm)
      // 提交之前做一个预处理
      this.$refs.addTabsFormRef.validate(async vdate => {
        if (!vdate) return false
        // 分类ID转换成以,分割的字符串
        this.addTabsForm.goods_cat = this.addTabsForm.goods_cat.join(',')
        // 商品的参数（数组），包含 动态参数 和 静态属性
        // 动态参数
        this.manyParamsData.forEach(item => {
          const manyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addTabsForm.attrs.push(manyInfo)
        })

        // 静态属性
        this.onlyParamsData.forEach(item => {
          const onlyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addTabsForm.attrs.push(onlyInfo)
        })
        // 发送请求
        const { data: res } = await this.$http.post('goods', this.addTabsForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 成功后提示
        this.$message.success(res.meta.msg)
        // 跳转到商品页面
        this.$router.push('/goods')
      })
    }
  },
  // 获取三级ID
  computed: {
    getGoodsCateId() {
      if (this.addTabsForm.goods_cat.length === 3) {
        return this.addTabsForm.goods_cat[this.addTabsForm.goods_cat.length - 1]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 !important;
  margin-right: 10px !important;
}

.el-image {
  margin: 20px auto;
}
</style>
